/**
 * New node file
 */
var globalConfigs = require("./globalConfigs.js");
var proto = require("../server/Proto/proto.js");
var dispatcher = require("../server/Dev/dispatcher.js");

function gateRegReplyHandler(cmd, c) {
	"use strict";
	console.error("gateRegReplyHandler");

}

var xx = 0;
function controllerCmdHandler(cmd, c) {
	"use strict";
	console.error("controllerCmdHandler");
	var bodyx = cmd.body;
	var ctrcmd = proto.parse(bodyx, "SCControllerCommand");
	console.error(ctrcmd);
	
	xx += 1;

	var newCmd = {};
	newCmd.devId = cmd.devId;
	newCmd.cmd = 4;
	newCmd.seq = cmd.seq;

	var body = {};
	body.replies = [];

	body.replies.push({
		index : 0,
		result : 0,
		status : 0
	});

	var buff = proto.pack(newCmd, body, "CSControllerCommandReply");
	function timeout() {
		c.write(buff);
	}
	
	c.write(buff);
//	if (xx !== 2) {
//		c.write(buff);
//	} else {
//		setTimeout(timeout, 40 * 1000);
//	}

}

var devHandlers = {
	1 : gateRegReplyHandler,
	5 : controllerCmdHandler,
	6 : controllerCmdHandler,
};

dispatcher.setCmdHandlers(devHandlers);

var normalPorts = [ {
	type : 1,
	appType : 1,
	index : 0,
	status : 0
}, {
	type : 1,
	appType : 1,
	index : 1,
	status : 0
}, {
	type : 2,
	appType : 2,
	index : 2,
	status : 0
}, {
	type : 2,
	appType : 2,
	index : 3,
	status : 0
} ];

function controllerReg(client, controllerPrefix) {
	"use strict";
	var v;
	for (v = 1; v < 10; v++) {
		var bcm = {};
		bcm.devId = controllerPrefix + v;
		bcm.cmd = 2;
		bcm.seq = 2;

		var body2 = {};
		body2.description = "controller-" + v;
		body2.ports = normalPorts;
		var buff = proto.pack(bcm, body2, "CSControllerReg");
		client.write(buff);
	}
}

function controllerLeave(client) {
	"use strict";
	var v;
	for (v = 1; v < 10; v++) {
		var bcm = {};
		bcm.devId = "xt-controller-" + v;
		bcm.cmd = 3;

		var buff = proto.pack(bcm);
		client.write(buff);
	}
}

function login(client, gwId, controllerPrefix) {
	"use strict";
	var bcm = {};
	bcm.devId = gwId;
	bcm.cmd = 1;
	bcm.seq = 1;

	var body = {};
	body.panId = "panId1";
	body.description = "stm32 gateway,256k";
	var buff = proto.pack(bcm, body, "CSGatewayReg");
	client.write(buff);

	function timeout() {
		controllerReg(client, controllerPrefix);
		// controllerLeave(client);
		// client.end();
	}

	setTimeout(timeout, 1 * 1000);
}

function setup(gwId, controllerPrefix) {
	"use strict";
	var net = require('net');
	var client = net.connect({
		port : globalConfigs.tPort
	}, function() { // 'connect' listener
		console.log('client connected');
		dispatcher(client);
		login(client, gwId, controllerPrefix);
	});

	client.on('end', function() {
		console.log('client disconnected');
	});
	client.on('error', function() {
		console.log('client error');
	});
}

for (var k = 47; k < 48; k += 1) {
	setup("test-gateway" + k, k + "-controller-");
}